import { useState, useEffect } from 'react';

// 定义 Todo 类型
interface Todo {
  id: string;
  text: string;
  completed: boolean;
  createdAt: Date;
}

// 定义过滤类型
type FilterType = 'all' | 'active' | 'completed';

function App() {
  const [todos, setTodos] = useState<Todo[]>(() => {
    const saved = localStorage.getItem('todos');
    return saved ? JSON.parse(saved) : [];
  });
  
  const [input, setInput] = useState('');
  const [filter, setFilter] = useState<FilterType>('all');
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editText, setEditText] = useState('');

  // 持久化存储
  useEffect(() => {
    localStorage.setItem('todos', JSON.stringify(todos));
    const bigdata = localStorage.getItem('bigdata');
    const dynamicArray = bigdata?JSON.parse(bigdata):[];
    for (let index = 0; index < 1000; index++) {
      const stationInfo = {
        "station_code": "25197",
        "station_name": "新县",
        "station_shortcode": "XXI",
        "statistics_code": "010",
        "subbureau_code": "39",
        "bureau_code": "N",
        "cwd_code": "",
        "station_shortname": "新",
        "station_class": "5",
        "station_state": "",
        "start_date": "19990101",
        "stop_date": "20991231",
        "station_id": "XSN",
        "city_code": "1220",
        "station_pycode": "Xinxian",
        "province_code": "13",
        "district_code": "2",
        "pinyin": "",
        "jianpin": "",
        "id": "XSN"
      };
      dynamicArray.push(stationInfo); // ["first"]
    }
    localStorage.removeItem('bigdata');
    console.log(dynamicArray.length)
    localStorage.setItem('bigdata',JSON.stringify(dynamicArray));

    const request = window.indexedDB.open('MyDatabase', 1);

    request.onupgradeneeded = (event) => {
      const db = (event.target as IDBOpenDBRequest).result;
      if (!db.objectStoreNames.contains('todos')) {
        db.createObjectStore('todos', { keyPath: 'id', autoIncrement: true });
      }
    };
    
    request.onsuccess = (event) => {
      console.log('Database opened successfully');
    };
    
    request.onerror = (event) => {
      console.error('Database opening error:', (event.target as IDBOpenDBRequest).error);
    };

  }, [todos]);

  // 添加 Todo
  const addTodo = (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim()) return;

    const newTodo: Todo = {
      id: crypto.randomUUID(),
      text: input.trim(),
      completed: false,
      createdAt: new Date()
    };

    setTodos([...todos, newTodo]);
    setInput('');
  };

  // 切换完成状态
  const toggleTodo = (id: string) => {
    setTodos(todos.map(todo => 
      todo.id === id ? { ...todo, completed: !todo.completed } : todo
    ));
  };

  // 删除 Todo
  const deleteTodo = (id: string) => {
    setTodos(todos.filter(todo => todo.id !== id));
  };

  // 开始编辑
  const startEdit = (todo: Todo) => {
    setEditingId(todo.id);
    setEditText(todo.text);
  };

  // 保存编辑
  const saveEdit = (id: string) => {
    setTodos(todos.map(todo =>
      todo.id === id ? { ...todo, text: editText.trim() } : todo
    ));
    setEditingId(null);
  };

  // 过滤后的 Todos
  const filteredTodos = todos.filter(todo => {
    if (filter === 'active') return !todo.completed;
    if (filter === 'completed') return todo.completed;
    return true;
  });

  // 剩余未完成数量
  const remaining = todos.filter(todo => !todo.completed).length;

  return (
    <div className="container">
      <h1>Todo List ({remaining} remaining)</h1>
      
      <form onSubmit={addTodo}>
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Add a new todo..."
        />
        <button type="submit">Add</button>
      </form>

      <div className="filters">
        {(['all', 'active', 'completed'] as FilterType[]).map(f => (
          <button
            key={f}
            className={filter === f ? 'active' : ''}
            onClick={() => setFilter(f)}
          >
            {f.charAt(0).toUpperCase() + f.slice(1)}
          </button>
        ))}
      </div>

      <ul>
        {filteredTodos.map(todo => (
          <li key={todo.id} className={todo.completed ? 'completed' : ''}>
            <input
              type="checkbox"
              checked={todo.completed}
              onChange={() => toggleTodo(todo.id)}
            />

            {editingId === todo.id ? (
              <input
                type="text"
                value={editText}
                onChange={(e) => setEditText(e.target.value)}
                onBlur={() => saveEdit(todo.id)}
                autoFocus
              />
            ) : (
              <span onDoubleClick={() => startEdit(todo)}>{todo.text}</span>
            )}

            <button onClick={() => deleteTodo(todo.id)}>Delete</button>
            <small>
              {new Date(todo.createdAt).toLocaleDateString()}
            </small>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;